<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/2
 * Time: 21:36
 * 收货地址接口
 */
namespace app\api\controller;

use app\common\controller\Api;
use think\Cache;
use think\Db;
use think\Exception;

/**
 * 收货地址
 * Class Address
 * @package app\api\controller
 */
class Address extends Api{
	
	protected $noNeedRight = ['*'];
	protected $noNeedLogin = ['areas', 'areadata'];
	
	
	/**
	 * 收货地址列表
	 */
	public function index(){
		$userId = $this->auth->id;
		$row = Db::name('address')->alias('ad')
			->join('area p','p.id = ad.province_id','left')
			->join('area c','c.id = ad.city_id','left')
			->join('area a','a.id = ad.area_id','left')
			->where(['ad.user_id' => $userId, 'ad.status' => 1])
			->field('ad.id, ad.recipients, ad.mobile, ad.address, ad.is_default, ad.province_id, ad.city_id, ad.area_id, p.areaname as province, c.areaname as city, a.areaname as area')
			->select();
		$this->success('查询成功',$row);
	}
	
	/**
	 * 添加修改收货地址
	 */
	public function editAddress(){
		$validate = new \app\common\validate\Address();
		$postData = input('post.');
		if(!$validate->check($postData)){
			$this->error($validate->getError());
		}
		
		$userId = $this->auth->id;
		$postData['user_id'] = $userId;
		
		Db::startTrans();
		try{
			if($postData['is_default'] == 1){
				$setRes = Db::name('Address')->where(['user_id' => $userId])->update(['is_default' => 0]);
				if($setRes === false){
					throw new Exception('添加出错，请稍候重试');
				}
			}
			
			$model = model('Address');
			if(isset($postData['id']) && !empty($postData['id'])){
				$res = $model->allowField(true)->save($postData,['id' => $postData]);
				$msg = '修改成功';
			} else {
				$res = $model->allowField(true)->isUpdate(false)->save($postData);
				$msg = '添加成功';
			}
			if(!$res){
				throw new Exception($model->getError());
			}
			
			Db::commit();
			$this->success($msg);
			
		} catch (Exception $e){
			Db::rollback();
			$this->error($e->getMessage());
		}
	}
	
	/**
	 * 删除收货地址
	 */
	public function delAddress(){
		$id = input('post.id');
		if(!$id){
			$this->error('请选择要删除的收货地址');
		}
		
		$userId = $this->auth->id;
		$where = ['id' => $id, 'user_id' => $userId];
		$row = model('address')->where($where)->find();
		if(!$row){
			$this->error('收货地址不存在');
		}
		
		
		Db::startTrans();
		try {
			$delRes = model('address')->save(['status' => 0], $where);
			if($delRes === false){
				throw new Exception('删除出错');
			}
			
			//更改新默认地址
			if($row['is_default']){
				$where = ['user_id' => $userId, 'status' => 1];
				$newRow = model('address')->where($where)->order(['id' => 'desc'])->find();
				if($newRow){
					$newRow->is_default = 1;
					$defRes = 	$newRow->save();
					
					if($defRes === false){
						throw new Exception('删除出错.');
					}
				}
				
			}
			
			Db::commit();
			$this->success('删除成功');
		} catch (Exception $e){
			Db::rollback();
			$this->error($e->getMessage());
		}
		
	}
	
	
	/**
	 * 获取所有地区
	 */
	public function areas()
	{
		
		if(!$dataArray = Cache::get('Address/areas')){
			$field = 'id as areaId,parentid as parent_id,areaname as areaName';
			$province = Db::name('area')->where(['parentid'=>0])->field($field)->select();
			
			
			foreach ($province as $v) {
				
				$city =  Db::name('area')->where(['parentid'=>$v['areaId']])->field($field)->select();
				if (isset($city) && !empty($city)) {
					foreach ($city as $c) {
						$v['cities'][$c['areaId']] = $c;
						$area =  Db::name('area')->where(['parentid '=> $c['areaId']])->field($field)->select();
						$v['cities'][$c['areaId']]['counties'] = $area ? $area : array();
					}
					$dataArray[] = $v;
				}
			}
			
			foreach ($dataArray as &$value) {
				if (isset($value['cities'])) {
					$value['cities'] = array_values($value['cities']);
				}
			}
			Cache::set('Address/areas', $dataArray, 3600);
		}
		$this->success('查询成功', array_values($dataArray));
	}
	
	/**
	 * 获取所有地区
	 */
	public function areadata()
	{
		$level = input('post.level', 1);
		
//		if(!$dataArray = Cache::get('Address/areas')){
			$field = 'id as value, areaname as label';
			$province = Db::name('area')->where(['parentid'=>0])->field($field)->select();
			if($level == 1) {
				$this->success('查询成功', $province);
			}
			
			$citys = [];
			$areas = [];
			foreach ($province as $v) {
				
				$city =  Db::name('area')->where(['parentid'=>$v['value']])->field($field)->select();
				$citys[] = $city;
				if (isset($city) && !empty($city)) {
					foreach ($city as $c) {
						$area =  Db::name('area')->where(['parentid '=> $c['value']])->field($field)->select();
						$areas[$v['value']][$c['value']] = $area;
					}
					$areas[$v['value']] = array_values($areas[$v['value']]);
					$dataArray[] = $v;
				}
			}
			
			if($level == 2) {
				$this->success('市查询成功', array_values($citys));
			}
			
			$this->success('区查询成功', array_values($areas));
			
			Cache::set('Address/areas', $dataArray, 3600);
//		}
		$this->success('查询成功', array_values($dataArray));
	}
}
